

package com.hazelcast.client.impl.spi.impl.discovery;

import com.hazelcast.client.impl.connection.AddressProvider;
import com.hazelcast.client.impl.connection.Addresses;
import com.hazelcast.client.impl.management.ClientConnectionProcessListenerRegistry;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.Member;

import java.util.Collections;
import java.util.List;

public class ViridianAddressProvider implements AddressProvider {

    private final HazelcastCloudDiscovery discovery;
    private volatile HazelcastCloudDiscovery.DiscoveryResponse response = new HazelcastCloudDiscovery.DiscoveryResponse(Collections.emptyMap(), Collections.emptyList());

    public ViridianAddressProvider(HazelcastCloudDiscovery discovery) {
        this.discovery = discovery;
    }

    @Override
    public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) throws Exception {
        response = discovery.discoverNodes();
        List<Address> addresses = response.getPrivateMemberAddresses();
        listenerRunner.onPossibleAddressesCollected(addresses);
        return new Addresses(addresses);
    }

    @Override
    public Address translate(Address address) throws Exception {
        if (address == null) {
            return null;
        }

        Address publicAddress = response.getPrivateToPublicAddresses().get(address);
        if (publicAddress != null) {
            return publicAddress;
        }

        response = discovery.discoverNodes();

        return response.getPrivateToPublicAddresses().get(address);
    }

    @Override
    public Address translate(Member member) throws Exception {
        return translate(member.getAddress());
    }
}
